package com.webservice;

import com.carpark.ejb.DAO.DAO;
import com.carpark.ejb.Model.ClientsModel;
import com.carpark.ejb.Model.PaymentsModel;
import com.carpark.ejb.Model.ReceivablesModel;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
 *
 * @author Krzysztof
 */
@ManagedBean
@ViewScoped
public class PaymentBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private final DAO dao = getSingleDao();
    DaoSingleObject dso;
    private ReceivablesModel currentReceivable;
    private Integer selectedRcvID;
    ClientsModel currentUser;
    List<ReceivablesModel> receivablesByClient;
    List<Bank> popularBanks;
    PaymentsModel currentPayment;
    private String rank;
    private LoginBean lg;
    List<PaymentsModel> paymentsByClient;
    private String transferTitle;
    private String paymentDateForUser;
    private String paymentTypeForUSer;
    SimpleDateFormat formatter;

    @PostConstruct
    public void init() {
        serverLog("nowy widok platnosci");
        setCurrentUser(dao.getClientById(getUserID()));
        popularBanks = createPopularBanks();
        formatter = new SimpleDateFormat("EEE d MMM yy", new Locale.Builder().setLanguage("pl").setRegion("PL").build());
    }

    public PaymentBean() {

        serverLog("tworzy nowy paymentBean");
    }

    public Integer getUserID() {
        if (this.lg == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            this.lg = (LoginBean) app.evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        }
        return this.lg.getId();
    }

    public ClientsModel getCurrentUser() {
        return currentUser;
    }

    public String getTransferTitle() {

        return transferTitle;
    }

    public DAO getSingleDao() {
        if (this.dso == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            this.dso = (DaoSingleObject) app.evaluateExpressionGet(context, "#{daoSingleObject}", DaoSingleObject.class);
        }
        return this.dso.dao;
    }

    public void setTransferTitle(String transferTitle) {
        this.transferTitle = transferTitle;
    }

    public String getPaymentDateForUser(ReceivablesModel rc) {
        this.currentPayment = getPaymentByReceivable(rc);
        String result = formatter.format(currentPayment.getPaymentDate());
        return result;
    }

    public void setPaymentDateForUser(String paymentDateForUser) {
        this.paymentDateForUser = paymentDateForUser;
    }

    public String getPaymentTypeForUSer(ReceivablesModel rc) {
        this.currentPayment = getPaymentByReceivable(rc);
        return PaymentType.Transfer.fromValueToLabel(currentPayment.getPaymentForm());
    }

    public PaymentsModel getCurrentPayment() {
        return currentPayment;
    }

    public void setCurrentPayment(PaymentsModel currentPayment) {
        this.currentPayment = currentPayment;
    }

    public void setPaymentTypeForUSer(String paymentTypeForUSer) {
        this.paymentTypeForUSer = paymentTypeForUSer;
    }

    public String getRank() {
        serverLog("pobieram rank: " + rank);
        return this.rank;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    public List<Bank> getPopularBanks() {
        return popularBanks;
    }

    public void setPopularBanks(List<Bank> popularBanks) {
        this.popularBanks = popularBanks;
    }

    public void setCurrentUser(ClientsModel currentUser) {
        this.currentUser = currentUser;
    }

    public LoginBean getLg() {
        return lg;
    }

    public List<ReceivablesModel> getReceivablesByClient() {
        if (receivablesByClient == null) {
            this.receivablesByClient = dao.getReceivablesByClient(currentUser);

        }
        return this.receivablesByClient;
    }

    public void setLg(LoginBean lg) {
        this.lg = lg;
    }

    public ReceivablesModel getCurrentReceivable() {
        serverLog(selectedRcvID + "");

        return currentReceivable;
    }

    public void setCurrentReceivable(ReceivablesModel currentReceivable) {
        serverLog("ustawiam naleznosc: " + currentReceivable);
        Calendar cal = Calendar.getInstance();
        cal.setTime(currentReceivable.getCreationDate());
        this.currentReceivable = currentReceivable;
        this.transferTitle = "Oplata[" + currentReceivable.getReceivableId() + "]" + cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DAY_OF_MONTH);
        serverLog("ustawiłem naleznosc: " + this.currentReceivable);
        this.rank = currentReceivable.getAmount() + "";
        serverLog("ustawiłem tytuł: " + this.transferTitle + " ustwiłem kwote: " + this.rank);

    }

    public void serverLog(String x) {
        Logger.getLogger(PaymentBean.class.getName()).log(Level.SEVERE, "[Carpark2013]: " + x);
    }

    public Integer getSelectedRcvID() {
        return selectedRcvID;
    }

    public void setSelectedRcvID(Integer selectedRcvID) {

        this.selectedRcvID = selectedRcvID;
        serverLog("ustawione: " + this.selectedRcvID);
    }

    public List<PaymentsModel> getPaymentsByClient() {
        if (paymentsByClient == null) {
            this.paymentsByClient = dao.getPaymentsByClient(currentUser);

        }
        return this.paymentsByClient;
    }

    public PaymentsModel getPaymentByReceivable(ReceivablesModel rcv) {
        PaymentsModel p = null;
        for (PaymentsModel py : getPaymentsByClient()) {
            if (rcv.equals(py.getReceivableId())) {
                p = py;
            }
        }
        return p;
    }

    protected void refreshPage() {
        FacesContext fc = FacesContext.getCurrentInstance();
        String refreshpage = fc.getViewRoot().getViewId();
        ViewHandler ViewH = fc.getApplication().getViewHandler();
        UIViewRoot UIV = ViewH.createView(fc, refreshpage);
        UIV.setViewId(refreshpage);
        fc.setViewRoot(UIV);
    }

    public List<Bank> createPopularBanks() {
        List<Bank> banks = new ArrayList<Bank>();
        banks.add(new Bank("https://www.ibnet24.pl/web-client/", "Invest Bank", "/css/images/Banks/InvestBank.gif"));
        banks.add(new Bank("https://www.bankmillennium.pl/osobiste/Default.qz?LanguageID=pl-PL", "Milenium", "/css/images/Banks/Milenium.gif"));
        banks.add(new Bank("https://www.ebgz.pl", "BGŻ", "/css/images/Banks/bgz.gif"));
        banks.add(new Bank("https://www.centrum24.pl/centrum24-web/login", "WBK", "/css/images/Banks/wbk.gif"));
        banks.add(new Bank("https://www.kb24.pl/", "Kredyt Bank 24", "/css/images/Banks/kredytBank.gif"));
        banks.add(new Bank("https://www.ipko.pl/", "PKO BP", "/css/images/Banks/pkoBP.gif"));
        banks.add(new Bank("https://inteligo.pl/secure", "Inteligo", "/css/images/Banks/inteligo.gif"));
        banks.add(new Bank("https://www.pekao24.pl/", "PEKAO SA", "/css/images/Banks/pekao.gif"));
        banks.add(new Bank("https://moj.multibank.pl/", "Multibank", "/css/images/Banks/multiBank.gif"));
        banks.add(new Bank("https://online.mbank.pl/pl/Login", "mbank", "/css/images/Banks/mbank.gif"));
        banks.add(new Bank("https://online.ingbank.pl/bskonl/login.html", "ING", "/css/images/Banks/ing.gif"));
        banks.add(new Bank("https://secure.getinonline.pl/", "GetIn Bank", "/css/images/Banks/getInBank.gif"));
        banks.add(new Bank("https://www.citibankonline.pl/PLGCB/JPS/portal/SignonLocaleSwitch.do?locale=pl_PL", "citibank", "/css/images/Banks/citiBank.gif"));
        banks.add(new Bank("https://www.bph.pl/pi/do/Login", "BPH", "/css/images/Banks/bph.gif"));
        banks.add(new Bank("https://ebank.db-pbc.pl/auth/login.jsp", "Deutsche Bank", "/css/images/Banks/deutsche.gif"));
        return banks;
    }

    public void addPayment(ActionEvent actionEvent) {

        FacesContext context = FacesContext.getCurrentInstance();
        serverLog("Rozpoczynam dodawanie płatności");
        PaymentsModel pay = new PaymentsModel(new Date(), "Transfer");
        ReceivablesModel rcv = dao.getReceivablesById(currentReceivable.getReceivableId());
        pay.setReceivableId(rcv);
        if (dao.addPayment(pay) == null) {
            context.addMessage(null, new FacesMessage("Wystąpił błąd", "Płatność nie została zaakceptowana"));
        } else {
            context.addMessage(null, new FacesMessage("Operacja zakończona sukcesem", "Twoja płatność została odnotowana"));
            refreshPage();
        }

    }
}
